package com.sf.wisdomkg.utils;

import android.animation.ValueAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.sf.wisdomkg.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2016/12/27.
 */
public class CommonUtils {

    public static String IP = "http://47.94.168.73";
    public static String M = "/jx_travel/";
    public static String IP_S = "http://60.205.214.21:8080";
//    public static String IP_S = "http://jy.dyit.net:8081/kindergarten";
    public static String M_T = "/kindergarten/app/teacher/";
    public static String M_S = "/kindergarten/app/parent/";

    private static Activity contentActivity;
    public static Dialog dialog;


    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /* 照相机缓存头像名称 */
    private static final String IMAGE_FILE_NAME_TEMP = "temp_faceImage.jpg";
    /* 头像名称 */
    private static final String IMAGE_FILE_NAME = "headImage.jpg";
    private static String IMGURL = null;
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    /**
     * 计算距离
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double GetDistance(double lat1, double lng1, double lat2, double lng2) {
        double r1 = rad(lat1);
        double r2 = rad(lng1);

        double a = rad(lat2);
        double b = rad(lng2);
        int R = 6378137;
        double s = Math.acos(Math.cos(r1) * Math.cos(a) * Math.cos(r2 - b) + Math.sin(r1) * Math.sin(a)) * R;
        s = Math.round(s * 10000) / 10000;
        return s;
    }


    // 把经纬度转换成度分秒显示
    private static String getLocationString(double input) {
        int du = (int) input;
        int fen = (((int) ((input - du) * 3600))) / 60;
        int miao = (((int) ((input - du) * 3600))) % 60;
        return String.valueOf(du) + "°" + String.valueOf(fen) + "′"
                + String.valueOf(miao) + "″";
    }

    //组装ip地址的方法
    public static String buildIP() {
        final String U;
        final String[] digitalArray = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        final String[] letterArray = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        U = letterArray[7] +
                letterArray[19] +
                letterArray[19] +
                letterArray[15] +
                "://" +
                digitalArray[1] +
                digitalArray[0] +
                digitalArray[1] +
                "." +
                digitalArray[2] +
                digitalArray[0] +
                digitalArray[1] +
                "." +
                digitalArray[3] +
                digitalArray[6] +
                "." +
                digitalArray[2] +
                digitalArray[3] +
                digitalArray[9];
        return U;
    }



    // 判断手机号的方法
    public static boolean isMobileNumber(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9])|(14[0-9])|(16[0-9])|(19[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    //判断地图拖拽经纬度
//    public static LatLng updateMapState(MapStatus status) {
//        LatLng latLng;
//        LatLng mCenterLatLng = status.target;
//        /**获取经纬度*/
//        double lat = mCenterLatLng.latitude;
//        double lng = mCenterLatLng.longitude;
//        latLng = new LatLng(lat, lng);
//        return latLng;
//    }

    //获取地图级别对应的比例
    public static int GetScale(int zoom) {
        int scale = 0;
        String a = Integer.toString(zoom);
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("18", "5000");
        hashMap.put("17", "5000");
        hashMap.put("16", "5000");
        hashMap.put("15", "5000");
        hashMap.put("14", "5000");
        hashMap.put("13", "5000");
        hashMap.put("12", "5000");
        hashMap.put("11", "10000");
        hashMap.put("10", "20000");
        hashMap.put("9", "25000");
        hashMap.put("8", "50000");
        hashMap.put("7", "100000");
        hashMap.put("6", "200000");
        hashMap.put("5", "500000");
        hashMap.put("4", "1000000");
        hashMap.put("3", "2000000");
        scale = Integer.parseInt(hashMap.get(a));

        return scale;

    }

    //字符串转时间戳
    public static String getTime(String timeString) {
        String timeStamp = null;
        SimpleDateFormat sdf;
//        sdf = new SimpleDateFormat("yyyy/MM/dd");
        sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        Date d;
        try {
            d = sdf.parse(timeString);
            long l = d.getTime();
            timeStamp = String.valueOf(l);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeStamp;
    }

    //时间戳转字符串
    public static String getStrTime(String timeStamp) {
        String timeString = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long l = Long.valueOf(timeStamp);
        timeString = sdf.format(new Date(l));//单位秒
        return timeString;
    }

    /**
     * 获取系统时间戳
     * @return
     */
    public static String getTimeStr(){

        long time=System.currentTimeMillis();//获取系统时间的10位的时间戳

        String  str=String.valueOf(time);

        return str;

    }
    /**
     * 通过Base32将Bitmap转换成Base64字符串
     *
     * @param bit
     * @return
     */
    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);// 参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }
    

    /**
     * 创建文件夹
     */
    private static void file(String str) {
        File destDir = new File(str);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
    }

    /**
     * 检测资源包是否存在
     *
     * @return
     */
    public static boolean fileIsExists() {
        try {
            File f = new File("/mnt/sdcard/Android/data/Arport/Arport");
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
// TODO: handle exception
            return false;
        }
        return true;
    }
    /**
     * 递归删除文件和文件夹
     *
     * @param file 要删除的根目录
     */
    public static void RecursionDeleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                RecursionDeleteFile(f);
            }
            file.delete();
        }

    }
    /**
     * 获取手机屏幕的宽高
     */
    public static int[] GetScreenWH(Activity activity){
        int [] wh = new int[2];
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("heigth : " + dm.heightPixels);
        System.out.println("width : " + dm.widthPixels);
        wh[0] = dm.widthPixels;
        wh[1] = dm.heightPixels;
        return wh;
    }

    /**
     * 屏幕可见区域包括状态栏
     * @param activity
     * @return
     */
    public static int[] getAreaOne(Activity activity){
        int [] wh = new int[2];
        Display disp = activity.getWindowManager().getDefaultDisplay();
        Point outP = new Point();
        disp.getSize(outP);
        wh[0] = outP.x ;
        wh[1] = outP.y;
        return wh;
    }

    /**
     * 屏幕应用区域不包括状态栏
     * @param activity
     * @return
     */
    public static int[] getAreaTwo(Activity activity){
        int [] wh = new int[2];
        Rect outRect = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
        System.out.println("top:"+outRect.top +" ; left: "+outRect.left) ;
        wh[0] = outRect.width();
        wh[1] = outRect.height();

        return wh;
    }

    /**
     * 屏幕绘制区域不包括状态栏 tabbar
     * @param activity
     * @return
     */
    public static int[] getAreaThree(Activity activity){
        int [] wh = new int[2];
        // 用户绘制区域
        Rect outRect = new Rect();
        activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(outRect);
        wh[0] = outRect.width() ;
        wh[1] = outRect.height();

        return wh;
    }
    /**
     * 提供（相对）精确的除法运算。当发生除不尽的情况时，由scale参数指
     * 定精度，以后的数字四舍五入。
     * @param v1 被除数
     * @param v2 除数
     * @param scale 表示表示需要精确到小数点以后几位。
     * @return 两个参数的商
     */
    public static double div(double v1, double v2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "The scale must be a positive integer or zero");
        }
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    public static int getStatusBarHeight(Context context){
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     * @param timeStr	时间戳
     * @return
     */
    public static String getStandardDate(String timeStr,String timeStr2) {
        long days = 0;
        long hours = 0;
        long minutes = 0;
        long diff = Long.parseLong(timeStr) - Long.parseLong(timeStr2);//这样得到的差值是微秒级别

        days = diff / (1000 * 60 * 60 * 24);
        hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
        minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);


        return days+"天"+hours+"小时"+minutes+"分";
    }


    //获取屏幕原始尺寸高度，包括虚拟功能键高度
    public static int getDpi(Context context){
        int dpi = 0;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics",DisplayMetrics.class);
            method.invoke(display, displayMetrics);
            dpi=displayMetrics.heightPixels;
        }catch(Exception e){
            e.printStackTrace();
        }
        return dpi;
    }
    /**
     * 获取 虚拟按键的高度
     * @param context
     * @return
     */
    public static  int getBottomStatusHeight(Context context){
        int totalHeight = getDpi(context);

        int contentHeight = getScreenHeight(context);

        return totalHeight  - contentHeight;
    }
    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context)
    {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 改变状态栏颜色
     * @param activity
     * @param colorResId
     */
    public static void setWindowStatusBarColor(Activity activity, int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = activity.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(activity.getResources().getColor(colorResId));

                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 判断摄像头是否可用
     * 主要针对6.0 之前的版本，现在主要是依靠try...catch... 报错信息，感觉不太好，
     * 以后有更好的方法的话可适当替换
     *
     * @return
     */
    public static boolean isCameraCanUse() {
        boolean canUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            // setParameters 是针对魅族MX5 做的。MX5 通过Camera.open() 拿到的Camera
            // 对象不为null
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            canUse = false;
        }
        if (mCamera != null) {
            mCamera.release();
        }
        return canUse;
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    public static void hideBottomUIMenu(Activity activity) {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = activity.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = activity.getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    /**
     * 处理大图片内存溢出
     * @param context
     * @param resId
     * @return
     */
    public static Bitmap readBitMap(Context context, int resId) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        return BitmapFactory.decodeStream(is, null, opt);
    }

    public static void onClickCenterToast(Activity activity,String string) {
        Toast toast = Toast.makeText(activity, string, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }


    //字符串转时间戳
    public static String getTimeD(String timeString) {
        String timeStamp = null;
        SimpleDateFormat sdf;

        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d;
        try {
            d = sdf.parse(timeString);
            long l = d.getTime();
            timeStamp = String.valueOf(l);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeStamp;
    }





    /**
     * 检测资源包是否存在
     *
     * @return
     */
    public static boolean fileIsExists(String url) {
        try {
            File f = new File(url);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
// TODO: handle exception
            return false;
        }
        return true;
    }


    /**
     * 计算listview的高度
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
    public static void performAnim2(String type, final View view, final BaseAdapter adapter){
        //View是否显示的标志

        //属性动画对象
        ValueAnimator va = null;
        if (type.equals("left")){
            va = ValueAnimator.ofInt(0,600);
            va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    //获取当前的height值
                    int h =(Integer)valueAnimator.getAnimatedValue();
                    //动态更新view的高度
                    view.getLayoutParams().width = h;
                    view.requestLayout();
                }
            });
            va.setDuration(400);
            //开始动画
            va.start();
        }else {
            va = ValueAnimator.ofInt(600,0);
            va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    //获取当前的height值
                    int h =(Integer)valueAnimator.getAnimatedValue();
                    //动态更新view的高度
                    view.getLayoutParams().width = h;
                    view.requestLayout();
                }
            });
            va.setDuration(400);
            //开始动画
            va.start();
        }
    }

    public static boolean fileIsExistsImg(String IMGURL){
        try{
            File f=new File(IMGURL);
            if(!f.exists()){
                return false;
            }

        }catch (Exception e) {
            // TODO: handle exception
            return false;
        }
        return true;
    }



    /**
     * 将时间戳转为代表"距现在多久之前"的字符串
     * @param timeStr	时间戳
     * @return
     */
    public static String getStandardDate(String timeStr) {
        long days = 0;
        long hours = 0;
        long minutes = 0;
        long diff = Long.parseLong(timeStr) - System.currentTimeMillis();//这样得到的差值是微秒级别

        days = diff / (1000 * 60 * 60 * 24);
        hours = (diff-days*(1000 * 60 * 60 * 24))/(1000* 60 * 60);
        minutes = (diff-days*(1000 * 60 * 60 * 24)-hours*(1000* 60 * 60))/(1000* 60);


        return days+"天"+hours+"小时"+minutes+"分";
    }


    /**
     * 省略手机中间几位
     * @param name
     * @return
     */
    public static String shenglue(String name){

        StringBuilder sb  =new StringBuilder();
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (i >= 3 && i <= 6) {
                sb.append('*');
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
    /**
     * 判断字符串是否只包含数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 修改头像方法
     */
    public static void showDialog(Activity activity) {
        IMGURL = Environment.getExternalStorageDirectory() + "/Android/data/"+ SystemContent.getPkName(activity)+"/";
        contentActivity = activity;
        View view = activity.getLayoutInflater().inflate(R.layout.photo_choose_dialog, null);
        dialog = new Dialog(activity, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ActionBar.LayoutParams(ActionBar.LayoutParams.FILL_PARENT,
                ActionBar.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = activity.getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

    }

    //     打开相册
    public static void openPhones() {
        Intent intentFromGallery = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intentFromGallery.setType("image/*"); // 设置文件类型
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        contentActivity.startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
    }

    // 打开照相机
    public static void openCamera() {
        // 打开相机
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用,存储缓存图片
        if (hasSdcard()) {
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(IMGURL + IMAGE_FILE_NAME_TEMP)));
        }
        contentActivity.startActivityForResult(intentFromCapture, CAMERA_REQUEST_CODE);
    }

 
    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public static void startPhotoZoom(Uri uri, Activity activity) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        activity.startActivityForResult(intent, 2);
    }
    /**
     *
     * @return
     * true表示 有sdcard false表示没有sdcard
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 弹窗提示
     */
    public static void confirm_info(final Activity activity, String content){
        DoubleButtonDialog.Builder builder = new DoubleButtonDialog.Builder(activity);
        builder.setMessage(content);
        builder.setTitle("温馨提示");
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setNegativeButton("确定",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();

                    }
                });

        builder.create().show();
    }
}
